package com.linuxgt.android.fileapp.service;

import android.content.Context;
import android.os.Environment;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * 文件服务类
 */

public class FileService {
    private Context context;

    public FileService(Context context) {
        this.context = context;
    }

    /**
     * 文件保存
     *
     * @param fileName    文件名
     * @param fileContent 文件内容
     * @throws Exception
     */
    public void save(String fileName, String fileContent) throws Exception {
        FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
        fileOutputStream.write(fileContent.getBytes());
        fileOutputStream.close();
    }

    public void saveToSDCard(String fileName,String fileContent) throws Exception{
        FileOutputStream fileOutputStream = new FileOutputStream(new File(Environment.getExternalStorageDirectory(),fileName),true);
        fileOutputStream.write(fileContent.getBytes());
        fileOutputStream.close();
    }

    /**
     * 文件读取
     * @param fileName 文件名
     * @return
     * @throws Exception
     */
    public String read(String fileName) throws Exception {
        FileInputStream fileInputStream = context.openFileInput(fileName);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        int index;
        while ((index = bufferedInputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, index < buffer.length ? index : buffer.length);
        }
        fileInputStream.close();
        return byteArrayOutputStream.toString();
    }
}
